package com.lazy.mongo.ex;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

public class DriverQuickTour {

    public void createConnection(){
        // To directly connect to a single MongoDB server
        // (this will not auto-discover the primary even if it's a member of a replica set)
        MongoClient mongoClient = new MongoClient();

        // or
        MongoClient mongoClient2 = new MongoClient("localhost");

        // or
        MongoClient mongoClient3 = new MongoClient("localhost", 27017);

        // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
        MongoClient mongoClient4 = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                new ServerAddress("localhost", 27018), new ServerAddress("localhost", 27019)));

        // or use a connection string
        MongoClientURI connectionString = new MongoClientURI("mongodb://localhost:27017,localhost:27018,localhost:27019");
        MongoClient mongoClient5 = new MongoClient(connectionString);

        MongoDatabase database = mongoClient5.getDatabase("mydb");
    }
    
    public void getConnection() {
        MongoClient mongoClient = new MongoClient();
        MongoDatabase database = mongoClient.getDatabase("mydb");
        MongoCollection<Document> collection = database.getCollection("test");
        
        // insert a Document
        /*
        {
            "name" : "MongoDB",
            "type" : "database",
            "count" : 1,
            "info" : {
                        x : 203,
                        y : 102
                      }
         }
         */
        Document doc = new Document("name", "MongoDB")
                .append("type", "database")
                .append("count", 1)
                .append("info", new Document("x", 203).append("y", 102));
        collection.insertOne(doc);
        
        
        // batch insert
        List<Document> documents = new ArrayList<Document>();
        for (int i = 0; i < 100; i++) {
            documents.add(new Document("i", i));
        }
        collection.insertMany(documents);
        
        
        // Collection count 
        System.out.println(collection.count());
    }
    
}
